#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <stdint.h>
#include <amqp.h>
#include <amqp_framing.h>
#include "utils.h"

int main(int argc, char const *argv[])
{
  amqp_connection_state_t conn;
  char *hostname = "localhost"; //argv[1];
  int port = 5672; //atoi(argv[2]);
  char *exchange = "nam_topic";
  char *exchangetype = "topic";
  int sockfd;
  char *routing_key = "nam.*.test";

  conn = amqp_new_connection();
  sockfd = amqp_open_socket(hostname, port);
  amqp_set_sockfd(conn, sockfd);
  amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, "guest", "guest");

  amqp_channel_open(conn, 1);
  amqp_get_rpc_reply(conn);

  amqp_bytes_t queuename;
  amqp_queue_declare_ok_t *r = amqp_queue_declare(conn, 1, amqp_cstring_bytes("nam_queue"), 0, 0, 0, 1, amqp_empty_table);
    queuename = amqp_bytes_malloc_dup(r->queue);

  amqp_queue_bind(conn, 1, queuename, amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key), amqp_empty_table);
  

  amqp_basic_consume(conn, 1, amqp_cstring_bytes("nam_queue"), amqp_empty_bytes, 0, 1, 0, amqp_empty_table);
  amqp_get_rpc_reply(conn);

  while (1) {
    
    amqp_frame_t frame;
    int result;

    amqp_basic_deliver_t *d;
    amqp_basic_properties_t *p;
    size_t body_target;
    size_t body_received;

      amqp_maybe_release_buffers(conn);
      result = amqp_simple_wait_frame(conn, &frame);
      
      // printf("Result %d\n", result);
      // printf("Frame type %d, channel %d\n", frame.frame_type, frame.channel);
      // printf("Method %s\n", amqp_method_name(frame.payload.method.id));
      // d = (amqp_basic_deliver_t *) frame.payload.method.decoded;
      // printf("Delivery %u, exchange %.*s routingkey %.*s\n",
       // (unsigned) d->delivery_tag,
       // (int) d->exchange.len, (char *) d->exchange.bytes,
       // (int) d->routing_key.len, (char *) d->routing_key.bytes);

      result = amqp_simple_wait_frame(conn, &frame);
      
      // p = (amqp_basic_properties_t *) frame.payload.properties.decoded;
      // printf("----\n");

      body_target = frame.payload.properties.body_size;
      body_received = 0;

      while (body_received < body_target) {
        result = amqp_simple_wait_frame(conn, &frame);
        body_received += frame.payload.body_fragment.len;
        amqp_dump(frame.payload.body_fragment.bytes,
        frame.payload.body_fragment.len);
      }

   }
  
  // amqp_bytes_t message_bytes;
  //amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS);
  //amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
  //amqp_destroy_connection(conn);
  return 0;
}